package com.rentong.wx.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Component
public class GaoDeMapUtil {
    private static final String API_URL = "https://restapi.amap.com/v3/geocode/regeo";
    private static final String KEY = "74226352574c0472571ae9fae159f8fe";

    /**
     * 参数:经度,纬度
     */
    public static String getProvinceCityDistrict(double longitude, double latitude) {
        String parameters = "?key=" + KEY;
        parameters += "&location=" + longitude + "," + latitude;
        parameters += "&extensions=all";
        parameters += "&output=JSON";

        String urlString = API_URL + parameters;
        StringBuilder res = new StringBuilder();

        try {
            URL url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("GET");
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = in.readLine()) != null) {
                res.append(line);
            }
            in.close();

            JSONObject json = JSONObject.parseObject(res.toString());
            if ("1".equals(json.getString("status"))) {
                JSONObject regeocode = json.getJSONObject("regeocode");
                JSONObject addressComponent = regeocode.getJSONObject("addressComponent");
                String province = addressComponent.getString("province");
                String city = addressComponent.getString("city");
                String district = addressComponent.getString("district");

                return "City:" + city + ", District:" + district;
            } else {
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    //根据地址获取经纬度
    public static Map getLonAndLat(String address) {
        // 返回输入地址address的经纬度信息, 格式是 经度,纬度
        String queryUrl = "http://restapi.amap.com/v3/geocode/geo?key=" + KEY + "&address=" + address;
        // 高德接口返回的是JSON格式的字符串
        String queryResult = getResponse(queryUrl);
        Map<String, String> map = new HashMap<String, String>();
        JSONObject obj = JSONObject.parseObject(queryResult);
        if (obj.get("status").toString().equals("1")) {
//            JSONObject jobJSON = JSONObject.parseObject(obj.get("geocodes").toString().substring(1, obj.get("geocodes").toString().length() - 1));
            JSONArray geocodes = obj.getJSONArray("geocodes");
            JSONObject firstGeocode = geocodes.getJSONObject(0);
            String location = firstGeocode.get("location").toString();
            String[] lonAndLat = location.split(",");
            if (lonAndLat != null && lonAndLat.length == 2) {
                map.put("lng", lonAndLat[0]);
                map.put("lat", lonAndLat[1]);
            }
//            System.out.println(map);
            return map;
        } else {
            throw new RuntimeException("地址转换经纬度失败，错误码：" + obj.get("infocode"));
        }
    }

    private static String getResponse(String serverUrl) {
        // 用JAVA发起http请求，并返回json格式的结果
        StringBuffer result = new StringBuffer();
        try {
            URL url = new URL(serverUrl);
            URLConnection conn = url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.toString();
    }


    public static String getCity(String longitude, String latitude) {
        String addressInfo = getProvinceCityDistrict(Double.parseDouble(longitude), Double.parseDouble(latitude));

        String[] parts = addressInfo.split(", "); // 拆分成 "City:大连市" 和 "District:甘井子区"
        String city = "";
        String district = "";
        for (String part : parts) {
            if (part.startsWith("City:")) {
                city = part.substring("City:".length()); // 获取 "市"
            } else if (part.startsWith("District:")) {
                district = part.substring("District:".length()); // 获取 "区"
            }
        }

//        System.out.println(longitude+","+latitude+"的城市区县为:"+addressInfo);
        System.out.println("City-------------: " + city);
//        System.out.println("District: " + district);

//        //城市先固定写死为南京市。。。。。。。。。。。。。。。。。。。。。。。。。
//        city = "南京市";

        return city;

    }

    /**
     * 根据两个定位点的经纬度算出两点间的距离
     *
     * @param startLonLat 起始经纬度
     * @param endLonLat   结束经纬度（目标经纬度）
     * @return 两个定位点之间的距离
     */
    public static double getDistance(String startLonLat, String endLonLat) {
        // 返回起始地startAddr与目的地endAddr之间的距离，单位：米
        String queryUrl = "http://restapi.amap.com/v3/distance?key="+KEY+"&type=0&origins="+startLonLat+"&destination="+endLonLat;
        String queryResult = getResponse(queryUrl);
        JSONObject job = JSONObject.parseObject(queryResult);
        JSONArray ja = job.getJSONArray("results");
        JSONObject jobO = JSONObject.parseObject(ja.getString(0));
        long result = Long.parseLong(jobO.get("distance").toString());
        return convertMetersToKm(result);
    }

    public static double convertMetersToKm(long meters) {
        return meters / 1000.0;  // 返回千米
    }

//    public static void main(String[] args) throws Exception  {
//        System.out.println(getAMapByLngAndLat("118.823040", "32.035849"));
//    }
    public static String getAMapByLngAndLat(String getLng, String getLat) throws Exception {
        String url;
        try {
            url = "http://restapi.amap.com/v3/geocode/regeo?output=JSON&location=" + getLng + ","
                    + getLat + "&key=" + KEY + "&radius=0&extensions=base";
            String queryResult = getResponse(url); // 高德接品返回的是JSON格式的字符串
            // 将获取结果转为json数据
            JSONObject obj = JSONObject.parseObject(queryResult);
            System.out.println(obj);
            if (obj.get("status").toString().equals("1")) {
                // 如果没有返回-1
                JSONObject regeocode = obj.getJSONObject("regeocode");
                if (regeocode.size() > 0) {
                    // 在regeocode中拿到 formatted_address 具体位置
                    return regeocode.get("formatted_address").toString();
                } else {
                    throw new RuntimeException("未找到相匹配的地址！");
                }
            } else {
                throw new RuntimeException("请求错误！");
            }
        } catch (Exception e) {

        }
        return "-1";
    }

//    public static void main(String[] args) throws InterruptedException {
//        double longitude = 118.760030;
//        double latitude = 32.068545;
//        String addressInfo = getProvinceCityDistrict(longitude, latitude);
//          System.out.println(addressInfo);
//        String[] parts = addressInfo.split(", "); // 拆分成 "City:大连市" 和 "District:甘井子区"
//        String city = "";
//        String district = "";
//        for (String part : parts) {
//            if (part.startsWith("City:")) {
//                city = part.substring("City:".length()); // 获取 "市"
//            } else if (part.startsWith("District:")) {
//                district = part.substring("District:".length()); // 获取 "区"
//            }
//        }
//        System.out.println(longitude+","+latitude+"的城市区县为:"+addressInfo);
//        System.out.println("City: " + city);
//        System.out.println("District: " + district);
//    }


}

